
<template>
  <div class="police-message">
    <el-card>
      <div class="top-search">
        <el-form :model="queryParams" label-width="auto" :inline="true" ref="queryFormRef">
          <el-form-item label="名称" prop="anName">
            <el-input v-model="queryParams.anName" placeholder="请输入通知名称"> </el-input>
          </el-form-item>

          <el-form-item label="通知方式" prop="anNotification">
            <el-select v-model="queryParams.anNotification" placeholder="通知方式" clearable style="width: 100%">
                <el-option v-for="dict in police_notice_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button plain @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-top">
        <el-button type="primary" @click="handler_add">增加</el-button>
        <el-button type="danger" :disabled="ids.length < 1" @click="handleDelete()">删除</el-button>
        <el-button plain @click="updataConfigMsgListFn">刷新配置文件</el-button>
      </div>
      <div class="table-content">
        <el-table ref="multipleTableRef" border height="65vh"
         :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column property="anName" label="通知名称" align="center" />
          <el-table-column property="anNotification" label="通知方式" align="center">
            <template #default="{row}">
              <dict-tag :options="police_notice_status" :value="row.anNotification" />
            </template>
          </el-table-column>
          <el-table-column property="anToken" label="地址" align="center" />
          <el-table-column property="anToken" label="操作" align="center" width="170px">
            <template #default="{row}">
              <el-button
              link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
              <el-button
              link type="primary" icon="EditPen" @click="editForm(row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <!-- 弹框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" 
    width="500"
    :close-on-click-modal="false">
      <div class="scroll_box">
        <el-form :model="form" label-width="auto" ref="ruleFormRef" :rules="rules">
          <el-form-item label="通知名称" prop="anName">
            <el-input v-model="form.anName" placeholder="请输入通知名称"/>
          </el-form-item>
          <el-form-item label="通知方式" prop="anNotification">
            <el-select v-model="form.anNotification" placeholder="通知方式" clearable style="width: 100%">
                <el-option v-for="dict in police_notice_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="地址" prop="anToken">
            <el-input v-model="form.anToken" placeholder="请输入webhook地址"/>
          </el-form-item>
          <el-form-item label="加签秘钥" prop="anSecretKey">
            <el-input v-model="form.anSecretKey" type="textarea" placeholder="请输入加签秘钥"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button @click="dialog.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
    
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElTable } from 'element-plus';
import { getConfigMsgListAPI, addConfigMsgAPI, deleteConfigMsgAPI, getConfigMsgInfoAPI, updataConfigMsgAPI, updataConfigMsgListAPI } from '@/api/police/message/index'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { police_notice_status } = toRefs<any>(proxy?.useDict("police_notice_status"));


const ruleFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();


const initForm = {
  anId: undefined,
  anName: "",
  anNotification: "",
  anToken: "",
  anSecretKey: "",
  anStatus: 0
}

const total = ref(1);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    anName: "",
    anNotification: ""
  },
  tableData: <any[]>[],
  form: { ...initForm },
  rules:{
    anName: [ { required: true, message: '通知名称不能为空', trigger: 'blur' } ],
    anNotification: [ { required: true, message: '通知方式不能为空', trigger: 'blur' } ],
    anToken: [ { required: true, message: 'webhook地址不能为空', trigger: 'blur' } ],
  }
});
const { queryParams, tableData, form, rules  } = toRefs(data);

const dialog = reactive({
  visible: false,
  title: "添加通知配置"
})

// 添加
const handler_add = async () => {
  dialog.visible = true
};

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);
let ids = ref<string[]>([])
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  ids.value = val.map(ele=>{ return ele.anId })
};

function handleQuery() {
  getList()
}

function resetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1
  handleQuery()
}

const getList = async () => {
  const res = await getConfigMsgListAPI(queryParams.value)
  if(res.code == 200) {
    tableData.value = res.rows
  }
};

function submit() {
  console.log(form.value)
  ruleFormRef.value?.validate(async(valid:boolean)=>{
    if(valid) {
      if(form.value.anId) {
        console.log("修改配置")
        const res = await updataConfigMsgAPI(form.value)
        if(res.code == 200) {
          ElMessage.success("修改配置成功！")
          resetForm()
          getList()
          dialog.visible = false
        }
      } else {
        const res = await addConfigMsgAPI(form.value)
        if(res.code == 200) {
          ElMessage.success("添加成功！")
          resetForm()
          getList()
          dialog.visible = false
        } else {
          ElMessage.error(res.msg)
        }
      }
    }
  })
}

function resetForm() {
  ruleFormRef.value?.resetFields();
  ruleFormRef.value?.clearValidate();
}

function handleDelete(row?:any) {
  const anIds = row?.anId || ids.value
  ElMessageBox.confirm(
      `是否确认删除所选择的选项！`,
      '提示',
      {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      }
  )
      .then(async () => {
          const res = await deleteConfigMsgAPI(anIds)
          if(res.code == 200) {
              ElMessage.success("删除成功！")
              getList()
          }
      })
      .catch(() => {
          ElMessage({
              type: 'info',
              message: '操作取消',
          })
      })
}

async function editForm(row:any) {
  const res = await getConfigMsgInfoAPI(row.anId)
  console.log("获取到的信息为", res)
  form.value = res.data
  dialog.visible = true
}

async function updataConfigMsgListFn() {
  const res = await updataConfigMsgListAPI()
  if(res.code==200) {
    ElMessage.success("配置文件刷新成功！")
  }
}

onMounted(()=>{
  getList()
})

defineExpose({
  getList
})

// provide('parentList',getList())
</script>
  
  <style scoped lang="scss">
.police-message {
  padding: 8px;
  width: 100%;
  height: 100%;
  .el-card {
    width: 100%;
    height: 100%;
    .table-top {
      margin-bottom: 20px;
    }
    .table-content {
      width: 100%;
    }
  }
}
</style>